<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue';

import { message } from 'ant-design-vue';

// 导入模态框组件
import AddTimeModal from './components/AddTimeModal.vue';
import TechnicianSettingsModal from './components/TechnicianSettingsModal.vue';

// 技师接口定义
interface Technician {
  id: string;
  name: string;
  gender: 'female' | 'male';
  department: string;
  employeeCard: string;
  productType: string;
  associatedProjects: string[];
  status: 'idle' | 'leave' | 'offDuty' | 'onCall' | 'onDuty' | 'rest';
  time: string;
  service: string;
  code: string;
  current: number;
  total: number;
}

// 任务接口定义
interface Task {
  id: string;
  technician: string;
  projectName: string;
  status: 'completed' | 'dispatched' | 'onCall';
  roomNumber: string;
  duration: string;
  createTime: string;
  dispatchMethod: 'direct' | 'rotation';
}

// 响应式数据
const selectedTechnician = ref<null | Technician>(null);

// 模态框状态
const modals = ref({
  addTime: false,
  endService: false,
  changeRoom: false,
  changeProject: false,
  changeTechnician: false,
  dispatchWork: false,
  technicianSettings: false,
});

// 筛选条件
const filters = ref({
  technicianType: 'all',
  technicianGender: 'all',
  technicianStatus: 'all',
  searchQuery: '',
});

// 右键菜单
const contextMenu = ref({
  visible: false,
  x: 0,
  y: 0,
  technician: null as null | Technician,
});

// 技师数据
const technicians = ref<Technician[]>([
  {
    id: '1001',
    name: '王雨然',
    gender: 'female',
    department: '按摩部',
    employeeCard: '21376023601',
    productType: '按摩类',
    associatedProjects: ['泰式按摩', '经脉按摩', '正骨按摩', '头皮按摩'],
    status: 'idle',
    time: '00:00:00',
    service: '空闲',
    code: 'A001',
    current: 0,
    total: 3,
  },
  {
    id: '1002',
    name: '李小明',
    gender: 'male',
    department: '按摩部',
    employeeCard: '21376023602',
    productType: '按摩类',
    associatedProjects: ['泰式按摩', '经脉按摩'],
    status: 'onDuty',
    time: '00:22:22',
    service: '泰式按摩',
    code: 'A002',
    current: 1,
    total: 3,
  },
  {
    id: '1003',
    name: '张美丽',
    gender: 'female',
    department: '美容部',
    employeeCard: '21376023603',
    productType: '美容类',
    associatedProjects: ['面部护理', '身体护理'],
    status: 'onCall',
    time: '00:06:00',
    service: '面部护理',
    code: 'B001',
    current: 1,
    total: 2,
  },
  // 生成更多技师数据
  ...Array.from({ length: 20 }, (_, i) => ({
    id: `${1004 + i}`,
    name: `技师${1004 + i}`,
    gender: i % 2 === 0 ? 'female' : 'male',
    department: i % 3 === 0 ? '按摩部' : i % 3 === 1 ? '美容部' : 'SPA部',
    employeeCard: `213760236${1004 + i}`,
    productType: i % 3 === 0 ? '按摩类' : i % 3 === 1 ? '美容类' : 'SPA类',
    associatedProjects: ['泰式按摩', '经脉按摩'],
    status: 'idle',
    time: '00:00:00',
    service: '空闲',
    code: `${String.fromCharCode(65 + (i % 3))}${String(i + 1).padStart(3, '0')}`,
    current: 0,
    total: 3,
  })),
]);

// 任务数据
const taskList = ref<Task[]>([
  {
    id: '1',
    technician: 'A001-王雨然',
    projectName: '泰式按摩',
    status: 'onCall',
    roomNumber: '2006',
    duration: '00:06:00',
    createTime: '2018/01/01 13:42:22',
    dispatchMethod: 'direct',
  },
  {
    id: '2',
    technician: 'A002-李小明',
    projectName: '经脉按摩',
    status: 'dispatched',
    roomNumber: '2007',
    duration: '00:45:00',
    createTime: '2018/01/01 13:30:00',
    dispatchMethod: 'rotation',
  },
  {
    id: '3',
    technician: 'B001-张美丽',
    projectName: '面部护理',
    status: 'onCall',
    roomNumber: '3001',
    duration: '00:15:00',
    createTime: '2018/01/01 13:35:00',
    dispatchMethod: 'direct',
  },
]);

// 任务表格列定义
const taskColumns = [
  { title: '技师', dataIndex: 'technician', key: 'technician' },
  { title: '项目名称', dataIndex: 'projectName', key: 'projectName' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '房间号', dataIndex: 'roomNumber', key: 'roomNumber' },
  { title: '应钟时长', dataIndex: 'duration', key: 'duration' },
  { title: '任务生成时间', dataIndex: 'createTime', key: 'createTime' },
  { title: '派工方式', dataIndex: 'dispatchMethod', key: 'dispatchMethod' },
  { title: '操作', key: 'operation' },
];

// 计算属性
const filteredTechnicians = computed(() => {
  let filtered = technicians.value;

  // 状态筛选
  if (filters.value.technicianStatus !== 'all') {
    filtered = filtered.filter(
      (tech) => tech.status === filters.value.technicianStatus,
    );
  }

  // 性别筛选
  if (filters.value.technicianGender !== 'all') {
    filtered = filtered.filter(
      (tech) => tech.gender === filters.value.technicianGender,
    );
  }

  // 搜索筛选
  if (filters.value.searchQuery) {
    const query = filters.value.searchQuery.toLowerCase();
    filtered = filtered.filter(
      (tech) =>
        tech.name.toLowerCase().includes(query) ||
        tech.id.toLowerCase().includes(query),
    );
  }

  return filtered;
});

const filteredTechnicianList = computed(() => {
  return technicians.value.filter((tech) => {
    // 技师类型筛选
    if (filters.value.technicianType !== 'all') {
      const typeMap = {
        massage: '按摩部',
        beauty: '美容部',
        spa: 'SPA部',
      };
      if (
        tech.department !==
        typeMap[filters.value.technicianType as keyof typeof typeMap]
      ) {
        return false;
      }
    }

    // 性别筛选
    if (
      filters.value.technicianGender !== 'all' &&
      tech.gender !== filters.value.technicianGender
    ) {
      return false;
    }

    // 状态筛选
    if (
      filters.value.technicianStatus !== 'all' &&
      tech.status !== filters.value.technicianStatus
    ) {
      return false;
    }

    // 搜索筛选
    if (filters.value.searchQuery) {
      const query = filters.value.searchQuery.toLowerCase();
      if (
        !tech.name.toLowerCase().includes(query) &&
        !tech.id.toLowerCase().includes(query)
      ) {
        return false;
      }
    }

    return true;
  });
});

// 状态统计
const statusStats = computed(() => {
  const stats = {
    idle: 0,
    onDuty: 0,
    onCall: 0,
    availableToEnd: 0,
    rest: 0,
    leave: 0,
    offDuty: 0,
  };

  technicians.value.forEach((tech) => {
    switch (tech.status) {
      case 'idle': {
        stats.idle++;
        break;
      }
      case 'leave': {
        stats.leave++;
        break;
      }
      case 'offDuty': {
        stats.offDuty++;
        break;
      }
      case 'onCall': {
        stats.onCall++;
        break;
      }
      case 'onDuty': {
        stats.onDuty++;
        break;
      }
      case 'rest': {
        stats.rest++;
        break;
      }
    }
  });

  // 可下钟数量（上钟中且时间超过一定阈值的技师）
  stats.availableToEnd = technicians.value.filter(
    (tech) => tech.status === 'onDuty' && tech.time !== '00:00:00',
  ).length;

  return stats;
});

// 任务统计
const taskStats = computed(() => {
  return {
    onDuty: taskList.value.filter((task) => task.status === 'dispatched')
      .length,
    availableToEnd: taskList.value.filter((task) => task.status === 'onCall')
      .length,
  };
});

// 右键菜单样式
const contextMenuStyle = computed(() => ({
  left: `${contextMenu.value.x}px`,
  top: `${contextMenu.value.y}px`,
}));

// 方法
const selectTechnician = (technician: Technician) => {
  selectedTechnician.value = technician;
};

const selectTechnicianFromList = (technician: Technician) => {
  selectedTechnician.value = technician;
};

const showContextMenu = (event: MouseEvent, technician: Technician) => {
  event.preventDefault();
  contextMenu.value = {
    visible: true,
    x: event.clientX,
    y: event.clientY,
    technician,
  };
};

const hideContextMenu = () => {
  contextMenu.value.visible = false;
};

const handleContextMenuAction = (action: string) => {
  if (contextMenu.value.technician) {
    selectedTechnician.value = contextMenu.value.technician;
  }

  contextMenu.value.visible = false;

  switch (action) {
    case 'addTime': {
      modals.value.addTime = true;
      break;
    }
    case 'changeProject': {
      message.success('换项目功能');
      break;
    }
    case 'changeRoom': {
      message.success('换房间功能');
      break;
    }
    case 'changeTechnician': {
      message.success('换技师功能');
      break;
    }
    case 'endService': {
      message.success('落钟功能');
      break;
    }
  }
};

const searchTechnician = () => {
  if (filters.value.searchQuery) {
    message.success(`搜索技师: ${filters.value.searchQuery}`);
  }
};

const dispatchWork = () => {
  message.success('派工功能');
};

const refreshData = () => {
  message.success('数据已刷新');
};

const onDuty = () => {
  message.success('值班功能已激活');
};

const changeShift = () => {
  message.success('换班功能已激活');
};

const startService = (task: Task) => {
  message.success(`技师 ${task.technician} 开始服务`);
};

const editTask = (task: Task) => {
  message.success(`编辑任务: ${task.id}`);
};

const cancelTask = (task: Task) => {
  message.success(`取消任务: ${task.id}`);
};

const goToManagement = () => {
  message.success('跳转到技师管理页面');
  // 实际跳转逻辑需要通过路由或导航来实现
};

// 生命周期
onMounted(() => {
  document.addEventListener('click', hideContextMenu);
});

onUnmounted(() => {
  document.removeEventListener('click', hideContextMenu);
});
</script>

<template>
  <div class="spa-technician-center">
    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧技师状态网格 -->
      <div class="technician-grid-container">
        <!-- 技师状态网格 -->
        <div class="technician-grid">
          <div
            v-for="technician in filteredTechnicians"
            :key="technician.id"
            class="technician-card"
            :class="`status-${technician.status}`"
            @click="selectTechnician(technician)"
            @contextmenu="showContextMenu($event, technician)"
          >
            <div class="technician-id">{{ technician.id }}</div>
            <div class="technician-time">{{ technician.time }}</div>
            <div class="technician-service">{{ technician.service }}</div>
            <div class="technician-code">{{ technician.code }}</div>
          </div>
        </div>

        <!-- 底部任务状态统计 -->
        <div class="task-statistics">
          <div class="statistics-info">
            <span>任务状态统计:</span>
            <span class="stat-item">上钟: {{ taskStats.onDuty }}</span>
            <span class="stat-item"
              >可下钟: {{ taskStats.availableToEnd }}</span
            >
          </div>
          <div class="action-buttons">
            <a-button type="primary" @click="dispatchWork">F1 派工</a-button>
            <a-button type="primary" @click="refreshData">F5 刷新</a-button>
          </div>
        </div>
      </div>

      <!-- 右侧技师列表面板 -->
      <div class="right-panel">
        <!-- 技师列表标题 -->
        <div class="panel-header">
          <h3>技师列表</h3>
        </div>

        <!-- 筛选区域 -->
        <div class="filter-section">
          <div class="filter-item">
            <label>技师类型:</label>
            <a-select
              v-model:value="filters.technicianType"
              placeholder="请选择技师类型"
            >
              <a-select-option value="all">全部</a-select-option>
              <a-select-option value="massage">按摩技师</a-select-option>
              <a-select-option value="beauty">美容技师</a-select-option>
              <a-select-option value="spa">SPA技师</a-select-option>
            </a-select>
          </div>
          <div class="filter-item">
            <label>技师性别:</label>
            <a-select
              v-model:value="filters.technicianGender"
              placeholder="请选择技师性别"
            >
              <a-select-option value="all">全部</a-select-option>
              <a-select-option value="male">男</a-select-option>
              <a-select-option value="female">女</a-select-option>
            </a-select>
          </div>
          <div class="filter-item">
            <label>技师状态:</label>
            <a-select
              v-model:value="filters.technicianStatus"
              placeholder="请选择技师状态"
            >
              <a-select-option value="all">全部</a-select-option>
              <a-select-option value="idle">空闲</a-select-option>
              <a-select-option value="onDuty">上钟</a-select-option>
              <a-select-option value="onCall">应钟</a-select-option>
              <a-select-option value="rest">休息</a-select-option>
              <a-select-option value="leave">请假</a-select-option>
            </a-select>
          </div>
          <div class="filter-item">
            <label>技师查询:</label>
            <div class="search-input">
              <a-input
                v-model:value="filters.searchQuery"
                placeholder="请输入技师姓名/编号"
                @keyup.enter="searchTechnician"
              />
              <a-button type="primary" @click="searchTechnician"> 🔍 </a-button>
            </div>
          </div>
        </div>

        <!-- 技师卡片网格 -->
        <div class="technician-cards-grid">
          <div
            v-for="tech in filteredTechnicianList"
            :key="tech.id"
            class="technician-mini-card"
            :class="`status-${tech.status}`"
            @click="selectTechnicianFromList(tech)"
          >
            <div class="tech-id">{{ tech.id }}</div>
            <div class="tech-ratio">({{ tech.current }}/{{ tech.total }})</div>
          </div>
        </div>

        <!-- 状态统计 -->
        <div class="status-statistics">
          <div class="stat-item">
            <span class="stat-label">空闲:</span>
            <span class="stat-value">{{ statusStats.idle }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">上钟:</span>
            <span class="stat-value">{{ statusStats.onDuty }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">应钟:</span>
            <span class="stat-value">{{ statusStats.onCall }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">可下钟:</span>
            <span class="stat-value">{{ statusStats.availableToEnd }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">休息:</span>
            <span class="stat-value">{{ statusStats.rest }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">请假:</span>
            <span class="stat-value">{{ statusStats.leave }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">落牌:</span>
            <span class="stat-value">{{ statusStats.offDuty }}</span>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <a-button type="primary" @click="onDuty">值班</a-button>
          <a-button type="primary" @click="changeShift">换班</a-button>
          <a-button type="primary" @click="goToManagement">技师管理</a-button>
        </div>
      </div>
    </div>

    <!-- 任务列表面板 -->
    <div class="task-panel">
      <div class="task-header">
        <h3>任务状态统计</h3>
        <div class="task-stats">
          <span>上钟: {{ taskStats.onDuty }}</span>
          <span>可下钟: {{ taskStats.availableToEnd }}</span>
        </div>
      </div>
      <div class="task-table">
        <a-table
          :columns="taskColumns"
          :data-source="taskList"
          :pagination="false"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'operation'">
              <a-button
                v-if="record.status === 'onCall'"
                type="primary"
                size="small"
                @click="startService(record)"
              >
                立即上钟
              </a-button>
              <a-button
                v-if="record.status === 'dispatched'"
                type="primary"
                size="small"
                @click="editTask(record)"
              >
                编辑任务
              </a-button>
              <a-button type="danger" size="small" @click="cancelTask(record)">
                取消任务
              </a-button>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <!-- 右键菜单 -->
    <div
      v-if="contextMenu.visible"
      class="context-menu"
      :style="contextMenuStyle"
    >
      <div class="menu-item" @click="handleContextMenuAction('addTime')">
        加钟
      </div>
      <div class="menu-item" @click="handleContextMenuAction('endService')">
        落钟
      </div>
      <div class="menu-item" @click="handleContextMenuAction('changeRoom')">
        换房间
      </div>
      <div class="menu-item" @click="handleContextMenuAction('changeProject')">
        换项目
      </div>
      <div
        class="menu-item"
        @click="handleContextMenuAction('changeTechnician')"
      >
        换技师
      </div>
    </div>

    <!-- 模态框组件 -->
    <AddTimeModal
      v-model:visible="modals.addTime"
      :technician="selectedTechnician"
    />
    <TechnicianSettingsModal v-model:visible="modals.technicianSettings" />
  </div>
</template>

<style scoped>
.spa-technician-center {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-height: 100vh;
  overflow: hidden;
  background-color: #f5f5f5;
}

.main-content {
  display: flex;
  flex: 1;
  min-height: 0;
  padding: 16px;
  padding-right: 320px;
  overflow: hidden;
  transition: padding-right 0.3s ease;
}

.technician-grid-container {
  position: relative;
  display: flex;
  flex: 1;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
  background: white;
  border-radius: 8px;
}

.technician-grid {
  display: grid;
  flex: 1;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 16px;
  min-height: 0;
  padding: 20px;
  overflow-y: auto;
}

.technician-card {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100px;
  padding: 8px;
  color: #333;
  cursor: pointer;
  background: #fafafa;
  border: 2px solid #d9d9d9;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.technician-card:hover {
  border-color: #40a9ff;
  box-shadow: 0 6px 20px rgb(0 0 0 / 15%);
  transform: translateY(-3px);
}

.technician-id {
  margin-bottom: 4px;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.technician-time {
  margin-bottom: 4px;
  font-size: 12px;
  font-weight: 500;
  color: #8c8c8c;
}

.technician-service {
  margin-bottom: 4px;
  font-size: 11px;
  font-weight: 400;
  color: #595959;
}

.technician-code {
  padding: 2px 6px;
  font-size: 10px;
  font-weight: 500;
  color: #1890ff;
  background: rgb(24 144 255 / 10%);
  border-radius: 4px;
}

/* 技师状态样式 */
.technician-card.status-idle {
  background: #fafafa;
  border-color: #d9d9d9;
}

.technician-card.status-onDuty {
  background: #f6ffed;
  border-color: #52c41a;
}

.technician-card.status-onCall {
  background: #fffbe6;
  border-color: #faad14;
}

.technician-card.status-rest {
  background: #f9f0ff;
  border-color: #722ed1;
}

.technician-card.status-leave {
  background: #fff2f0;
  border-color: #ff4d4f;
}

.technician-card.status-offDuty {
  background: #f5f5f5;
  border-color: #8c8c8c;
}

/* 任务统计区域 */
.task-statistics {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 20px;
  background: #fafafa;
  border-top: 1px solid #f0f0f0;
}

.statistics-info {
  display: flex;
  gap: 16px;
  align-items: center;
}

.stat-item {
  font-weight: 500;
  color: #1890ff;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

/* 右侧面板样式 */
.right-panel {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
  display: flex;
  flex-direction: column;
  gap: 16px;
  width: 300px;
  max-height: 100vh;
  padding: 16px;
  padding-top: 80px;
  overflow-y: auto;
  background: white;
  border-left: 1px solid #d9d9d9;
  box-shadow: -2px 0 8px rgb(0 0 0 / 10%);
  transition: all 0.3s ease;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.filter-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.filter-item label {
  font-size: 12px;
  font-weight: 500;
  color: #595959;
}

.search-input {
  display: flex;
  gap: 4px;
}

.technician-cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));
  gap: 8px;
  max-height: 200px;
  overflow-y: auto;
}

.technician-mini-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50px;
  padding: 4px;
  cursor: pointer;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.technician-mini-card:hover {
  border-color: #40a9ff;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.technician-mini-card.status-idle {
  background: #f6ffed;
  border-color: #52c41a;
}

.technician-mini-card.status-onDuty {
  background: #fffbe6;
  border-color: #faad14;
}

.technician-mini-card.status-onCall {
  background: #e6f7ff;
  border-color: #1890ff;
}

.technician-mini-card.status-rest {
  background: #f9f0ff;
  border-color: #722ed1;
}

.technician-mini-card.status-leave {
  background: #fff2f0;
  border-color: #ff4d4f;
}

.technician-mini-card.status-offDuty {
  background: #f5f5f5;
  border-color: #8c8c8c;
}

.tech-id {
  font-size: 12px;
  font-weight: 600;
  color: #262626;
}

.tech-ratio {
  font-size: 10px;
  color: #8c8c8c;
}

.status-statistics {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
  padding: 12px;
  background: #fafafa;
  border-radius: 4px;
}

.stat-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.stat-label {
  font-size: 12px;
  color: #595959;
}

.stat-value {
  font-size: 14px;
  font-weight: 600;
  color: #1890ff;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

/* 任务面板样式 */
.task-panel {
  height: 300px;
  background: white;
  border-top: 1px solid #d9d9d9;
}

.task-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 20px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.task-header h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.task-stats {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #595959;
}

.task-table {
  height: calc(100% - 50px);
  overflow-y: auto;
}

/* 右键菜单样式 */
.context-menu {
  position: fixed;
  z-index: 1000;
  min-width: 120px;
  padding: 4px 0;
  background: white;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  box-shadow: 0 4px 12px rgb(0 0 0 / 15%);
}

.menu-item {
  padding: 8px 12px;
  font-size: 14px;
  color: #262626;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.menu-item:hover {
  background-color: #f5f5f5;
}
</style>
